#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QNetworkDatagram>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //创建udp对象
    socket = new QUdpSocket(this);
    //设置窗口标题
    this->setWindowTitle("服务器");
    //连接信号槽
    connect(socket, &QUdpSocket::readyRead, this, &Widget::processRequest);

    //绑定端口号
    bool retbind = socket->bind(QHostAddress::Any, 8082);
    if(retbind == false)
    {
        QMessageBox::critical(this, "服务器启动出错", socket->errorString());
        return;
    }

}

Widget::~Widget()
{
    delete ui;
}

//但是我们这里是回显，所以没有什么处理过程
QString Widget::porcess(const QString &request)
{
    return request;
}

void Widget::processRequest()
{
    //获取请求信息
    const QNetworkDatagram& udp_request =  socket->receiveDatagram();
    //转化为字符串类型
    QString data_request = udp_request.data();

    //处理请求
    const QString& data = porcess(data_request);

    //构建相应数据报
    QNetworkDatagram response(data.toUtf8(), udp_request.senderAddress(), udp_request.senderPort());
    //发送回客户端
    socket->writeDatagram(response);
    //把客户端发的信息显示到listWidget控件上
    QString log = "[" + udp_request.senderAddress().toString() + ":" + QString::number(udp_request.senderPort())
            + "]" + "message:" + data_request;
    ui->listWidget->addItem(log);
}


























